package com.zl.learning.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VolatileTest {

    static class User {
        int age = 0;
        String name;

        public User() {
            age = 8;
            name = "zhangsan";
        }

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    private static User user;
    private static final Object LOCK = new Object();

    public static void main(String[] args) {
        final ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    if (user != null) {
                        System.out.println(user);
                    }
                    if (user == null) {
                        synchronized (LOCK) {
                            if (user == null) {
                                user = new User();
                            }
                        }
                    }
                    if (user.age == 0) {
                        System.out.println(user);
                    }
                }
            });
        }
        executorService.shutdown();
    }

}
